package com.itany.shop.controller;

import com.itany.shop.entity.User;
import com.itany.shop.exception.*;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.vo.Cart;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 石小俊
 * @date 2023年07月05日 17:00
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path){
            case "/register.user":
                register(request,response);
                break;
            case "/register2.user":
                register2(request,response);
                break;
            case "/login.user":
                login(request,response);
                break;
            case "/logout.user":
                logout(request,response);
                break;
            default:
                PrintWriter out = response.getWriter();
                out.println("<h1 style='color:red;'>您输入的请求有误,请重新输入</h1>");
                break;
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/findAll.product");
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService = (UserService) ObjectFactory.getObject("userService");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String image = (String) request.getSession().getAttribute("code");

        try {
            User user = userService.login(username,password,code,image);
            request.getSession().setAttribute("user",user);

            // 当用户成功登录之后,为当前用户分配一个新的购物车
            request.getSession().setAttribute("cart",new Cart());

            response.sendRedirect(request.getContextPath()+"/findAll.product");
        } catch (RequestParameterErrorException e) {
            request.setAttribute("loginMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        } catch (CodeErrorException e) {
            request.setAttribute("loginMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        } catch (UserNotExistException e) {
            request.setAttribute("loginMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }

    }

    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService = (UserService) ObjectFactory.getObject("userService");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        try {
            userService.register(username,password,phone,address);
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
        } catch (RequestParameterErrorException e) {
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (UserExistException e) {
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        }
    }

    protected void register2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserService userService = (UserService) ObjectFactory.getObject("userService");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items = upload.parseRequest(request);
            Map<String,FileItem> map = new HashMap<>();
            for(FileItem item : items){
                map.put(item.getFieldName(),item);
            }
            String username = map.get("username").getString("UTF-8");
            String password = map.get("password").getString("UTF-8");
            String phone = map.get("phone").getString("UTF-8");
            String address = map.get("address").getString("UTF-8");
            FileItem file = map.get("file");
            userService.register(username,password,phone,address,file,request.getSession());
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
        } catch (FileUploadException e) {
            request.setAttribute("registerMsg","头像解析失败");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        }  catch (RequestParameterErrorException e) {
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (UserExistException e) {
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (FileUploadErrorException e) {
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        }
    }
}
